package roslan.musicbox.server.data;

import java.text.DecimalFormat;
import roslan.musicbox.exception.TagVersionFormatException;

public class MusicTagVersion {
	//O000331 is the 331st version of official database.
	//U000211_roach is the user-presented 211st version by roach.
	public enum TagSource{Official, User};
	private TagSource source;
	private int version;
	private String author;
	
	public MusicTagVersion clone(){
		MusicTagVersion mtv = new MusicTagVersion();
		mtv.source = this.source;
		mtv.version = this.version;
		mtv.author = this.author;
		return mtv;
	}
	
	public TagSource getSource(){
		return source;
	}
	
	public int getVersion(){
		return version;
	}
	
	public String getAuthor(){
		return author;
	}
	
	public void setSource(TagSource source){
		this.source = source;
	}
	
	public void setVersion(int version){
		if(version<0) return;
		this.version = version;
	}
	
	public void setAuthor(String author){
		this.author = author;
	}
	
	public String getInfo(){
		StringBuffer info = new StringBuffer("");
		if(source == TagSource.Official){
			info.append("O");
		}else{
			info.append("U");
		}
		info.append(new DecimalFormat("000000").format(version));
		if(source == TagSource.User){
			info.append("_"+author);
		}
		return info.toString();
	}
	
	public String toString(){
		return getInfo();
	}
	
	public static MusicTagVersion getTagVersionFromInfo(String info)
	throws TagVersionFormatException{
		MusicTagVersion tagVersion = new MusicTagVersion();
		if(info.charAt(0)=='O'){
			tagVersion.source = TagSource.Official;
		}else if(info.charAt(0)=='U'){
			tagVersion.source = TagSource.User;
		}else{
			throw new TagVersionFormatException();
		}
		if(tagVersion.source == TagSource.Official){
			String verStr = info.substring(1);
			try{
				tagVersion.version = Integer.valueOf(verStr);
			}catch(Exception e){
				throw new TagVersionFormatException();
			}
			tagVersion.author = "";
		}else{
			int pos = info.indexOf('_');
			if(pos<0){
				throw new TagVersionFormatException();
			}
			String verStr = info.substring(1,pos);
			try{
				tagVersion.version = Integer.valueOf(verStr);
			}catch(Exception e){
				throw new TagVersionFormatException();
			}
			tagVersion.author = info.substring(pos+1);
		}
		return tagVersion;
	}
}
